/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Tipo_Despesa.java
 *
 * Created on 10/10/2012, 21:37:38
 */

package projeto;

import java.util.ArrayList;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import projeto.classes.ModeloTipoDespesa;
import projeto.classes.TipoDespesaAcessaDados;
/**
 *
 * @author Angela
 */
public class Tipo_Despesa extends javax.swing.JInternalFrame {

    ModeloTipoDespesa td;
    TipoDespesaAcessaDados tdDao;
    ArrayList<ModeloTipoDespesa> lista;
    /** Creates new form Tipo_Despesa */
    public Tipo_Despesa() {
        //somente admins acessam
        initComponents();
        btnAlterar.setEnabled(false);
        btnExcluir.setEnabled(false);
        txtTipo.setEnabled(false);
        cmbPesquisa.setEnabled(false);
        
        td = new ModeloTipoDespesa();
        tdDao = new TipoDespesaAcessaDados();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtConsulta = new javax.swing.JTextField();
        btnConsultar = new javax.swing.JToggleButton();
        cmbPesquisa = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        lblCodigo = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtTipo = new javax.swing.JTextField();
        btnNovo = new javax.swing.JButton();
        btnAlterar = new javax.swing.JButton();
        btnSair = new javax.swing.JButton();
        btnExcluir = new javax.swing.JButton();

        setTitle("Entrega Gado - Tipo de Despesa");

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setText("TIPO DE DESPESA");

        jLabel3.setText("Consultar por:");

        btnConsultar.setText("Consultar");
        btnConsultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConsultarActionPerformed(evt);
            }
        });

        cmbPesquisa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbPesquisaActionPerformed(evt);
            }
        });

        jLabel4.setText("Código:");

        lblCodigo.setText("--");

        jLabel2.setText("Tipo:");

        txtTipo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtTipoActionPerformed(evt);
            }
        });

        btnNovo.setText("Novo");
        btnNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNovoActionPerformed(evt);
            }
        });

        btnAlterar.setText("Alterar");
        btnAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAlterarActionPerformed(evt);
            }
        });

        btnSair.setText("Sair");
        btnSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSairActionPerformed(evt);
            }
        });

        btnExcluir.setText("Excluir");
        btnExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(79, 79, 79)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(43, 43, 43)
                                .addComponent(jLabel1))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txtTipo, javax.swing.GroupLayout.PREFERRED_SIZE, 221, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(68, 68, 68)
                        .addComponent(jLabel4)))
                .addContainerGap(60, Short.MAX_VALUE))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(38, 38, 38)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel3)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(cmbPesquisa, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(txtConsulta))
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(btnConsultar))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(lblCodigo)
                                    .addGap(0, 231, Short.MAX_VALUE))))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(20, 20, 20)
                            .addComponent(btnNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(18, 18, 18)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(btnAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(18, 18, 18)
                                    .addComponent(btnSair, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGap(0, 0, Short.MAX_VALUE)))
                    .addGap(38, 38, 38)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(67, 67, 67)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(131, Short.MAX_VALUE))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(41, 41, 41)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtConsulta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btnConsultar)
                        .addComponent(jLabel3))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(cmbPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(9, 9, 9)
                    .addComponent(lblCodigo)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 59, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(btnNovo)
                        .addComponent(btnAlterar)
                        .addComponent(btnSair))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(btnExcluir)
                    .addGap(42, 42, 42)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConsultarActionPerformed
        if (txtConsulta.getText().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Informe o tipo para consulta", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
        } else {
            //seta o ArrayList para null, limpa o resultado da consulta anterior
            lista = null;
            String filtro = "tp_despesa LIKE '" + txtConsulta.getText() + "%'";

            try {
                lista = tdDao.consulta(filtro);
                
                if (lista.isEmpty()) {
                    JOptionPane.showMessageDialog(this, "Não foram localizados tipos com o nome " + txtConsulta.getText(), "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
                }

                if (lista.size() > 0) {
                    if (cmbPesquisa.getItemCount() > 0) {
                        cmbPesquisa.removeAllItems();
                    }
                    cmbPesquisa.setEnabled(true);
                    btnAlterar.setEnabled(true);
                    btnExcluir.setEnabled(true);
                    btnNovo.setText("Novo");
                    txtTipo.setEnabled(false);

                    //seleciona o 1º (ou o unico) item da lista
                    ModeloTipoDespesa modeloTd = lista.get(0);
                    cmbPesquisa.addItem(modeloTd.getTipoDespesa());
                    cmbPesquisa.setSelectedIndex(0);
                }

                if (lista.size() > 1) {
                    //apenas inclui os outros componentes na lista (se houver)
                    for (int i = 1; i <= lista.size() - 1; i++) {
                        ModeloTipoDespesa modeloTd = lista.get(i);
                        cmbPesquisa.addItem(modeloTd.getTipoDespesa());
                    }
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "Erro ao consultar " + ex.getMessage(), "Entrega Gado", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_btnConsultarActionPerformed

    private void cmbPesquisaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbPesquisaActionPerformed
        if (evt.getSource().getClass().getSimpleName().equals("JComboBox")) {
            JComboBox cmb = (JComboBox)evt.getSource();
            int index = cmb.getSelectedIndex();
            if (index != -1) {
                ModeloTipoDespesa modeloTd = lista.get(index);
                String id = modeloTd.getId() + "";
                String tipo = modeloTd.getTipoDespesa();
                lblCodigo.setText(id);
                txtTipo.setText(tipo);
            }
        }
    }//GEN-LAST:event_cmbPesquisaActionPerformed

    private void txtTipoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtTipoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtTipoActionPerformed

    private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed
        if (btnNovo.getText().equals("Novo")) {
            txtTipo.setEnabled(true);
            txtTipo.setText("");
            lblCodigo.setText("--");
            btnAlterar.setEnabled(false);
            btnNovo.setText("Salvar");
            btnAlterar.setEnabled(false);
            btnExcluir.setEnabled(false);
        } else {
            //clicou no salvar
            if (txtTipo.getText().isEmpty()) {
                JOptionPane.showMessageDialog(this, "Informe o tipo para salvar", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
            } else {
                td.setTipoDespesa(txtTipo.getText());

                try {
                    if (!tdDao.incluir(td)) {
                        JOptionPane.showMessageDialog(this, "Dados gravados", "Cliente", JOptionPane.INFORMATION_MESSAGE);
                        btnNovo.setText("Novo");
                        btnAlterar.setEnabled(true);
                        txtTipo.setEnabled(false);
                        int maxId = tdDao.consultaMaxId();
                        lblCodigo.setText(maxId + "");
                        btnExcluir.setEnabled(true);
                    }

                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(this, "Erro ao gravar " + ex.getMessage(), "Entrega Gado", JOptionPane.ERROR_MESSAGE);
                }

            }

        }
    }//GEN-LAST:event_btnNovoActionPerformed

    private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarActionPerformed
        if (btnAlterar.getText().equals("Alterar")) {
            txtTipo.setEnabled(true);
            btnAlterar.setText("Salvar");
            btnExcluir.setEnabled(false);
        } else {
            if (txtTipo.getText().isEmpty()) {
                JOptionPane.showMessageDialog(this, "Informe o tipo para alterar", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
            } else {
                td.setId(Integer.parseInt(lblCodigo.getText()));
                td.setTipoDespesa(txtTipo.getText());

                try {
                    if (tdDao.alterar(td) > 0) {
                        JOptionPane.showMessageDialog(this, "Dados alterados", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
                        btnAlterar.setText("Alterar");
                        txtTipo.setEnabled(false);
                        btnExcluir.setEnabled(true);
                    }

                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(this, "Erro ao gravar " + ex.getMessage(), "Entrega Gado", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }//GEN-LAST:event_btnAlterarActionPerformed

    private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnSairActionPerformed

    private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
        if (txtTipo.getText().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Selecione um tipo", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
        } else {
            try {
                int id = Integer.parseInt(lblCodigo.getText());

                if (tdDao.deletar(id) == 1) {
                    JOptionPane.showMessageDialog(this, "Registro excluido", "Entrega Gado", JOptionPane.INFORMATION_MESSAGE);
                    txtTipo.setText("");
                    btnExcluir.setEnabled(false);
                    btnAlterar.setEnabled(false);
                }

            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "Erro ao excluir " + ex.getMessage(), "Entrega Gado", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_btnExcluirActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAlterar;
    private javax.swing.JToggleButton btnConsultar;
    private javax.swing.JButton btnExcluir;
    private javax.swing.JButton btnNovo;
    private javax.swing.JButton btnSair;
    private javax.swing.JComboBox cmbPesquisa;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel lblCodigo;
    private javax.swing.JTextField txtConsulta;
    private javax.swing.JTextField txtTipo;
    // End of variables declaration//GEN-END:variables

}
